<?php

namespace app\controllers\Student;
use Yii;
use app\controllers\BaseController;
use app\common\parser\JsonParser;
use app\common\api\ApiOperator; //引入访问api类
use yii\data\Pagination;
use yii\helpers\Url;
use app\common\helper\PdUtils;
use app\models\TQuizQuestion;
use app\models\TQuizQuestionAnswer;
use app\models\TQuizStudentQuesExercise;
use Faker\Provider\Uuid;

class StudentQuesExerciseController extends BaseController
{
    
    public function actionIndex(){
        $tcourseId=$_GET['tcourseId'];
        BaseController::checkUserAccess($tcourseId, 'student-class');
        $userId = \Yii::$app->user->identity->id;
        $session = Yii::$app->session;      
        $bcourseId = $session->get('joinCourseInfo')[$tcourseId]['bCourseId'];
        $joinCourseInfo=$session->get('joinCourseInfo');
        $projectId = empty($joinCourseInfo[$tcourseId]['project_id'])?PdUtils::getTcourseProjectId($tcourseId):$joinCourseInfo[$tcourseId]['project_id'];
        $tcourseOldId = empty($joinCourseInfo[$tcourseId]['t_old_id'])?PdUtils::getOldId('t_course_info',$tcourseId):$joinCourseInfo[$tcourseId]['t_old_id'];
        $bcourseOldId=empty($joinCourseInfo[$tcourseId]['b_old_id'])?PdUtils::getOldIdByTid($tcourseId):$joinCourseInfo[$tcourseId]['b_old_id'];

//        $sql = "select count(id) num from t_quiz_student_ques_exercise where create_by=:studentId and del_flag=:d and b_course_id=:b_course_id and t_course_id=:t_course_id ";
//        $error_sql = $sql." and is_correct='yesOrNo.no'";
        $sql = "select count(e.id) num from t_quiz_student_ques_exercise e "
                . "left join t_quiz_question q on q.id=e.ques_id "
                . "where e.create_by=:studentId and e.del_flag=:d and e.b_course_id=:b_course_id and e.t_course_id=:t_course_id ";
        $error_sql = $sql." and (is_correct='yesOrNo.no' or q.type in('questionType.fillIn','questionType.shortAnswer','questionType.discuss','questionType.calculation'))";
        $error = Yii::$app->db->createCommand($error_sql)->bindValues([':studentId'=>$userId,':d'=>0,':b_course_id'=>$bcourseId,':t_course_id'=>$tcourseId])->queryScalar();

        $yida = Yii::$app->db->createCommand($sql)->bindValues([':studentId'=>$userId,':d'=>0,':b_course_id'=>$bcourseId,':t_course_id'=>$tcourseId])->queryScalar();

        $ques_sql="select q.* from t_quiz_course_ques_relation course_q 
            left join t_quiz_question q on q.id = course_q.question_id 
            left join t_quiz_paper_ques_relation r on r.ques_id = q.id
            where course_q.course_id='".$bcourseId."' and q.status='questionStatus.approved' and q.del_flag=0 and course_q.del_flag=0 group by q.id order by q.create_time desc";
        $count = Yii::$app->db->createCommand($ques_sql)->queryAll();
        $count = count($count);
        //用行为日志：打开学生考试测验页面
        $m_data=[
            'userid'=> \Yii::$app->user->identity->old_id,
            'time'=> date('Y-m-d H:i:s'),
            'ip'=> \Yii::$app->request->userIP,
            'equipment'=> PdUtils::EQUIPMENT_PC,
            'operation_code'=>'15010026',
            'operation_name'=>'打开考试测试列表模块',
            'courseid'=>$tcourseOldId,
            'objectid'=>$tcourseOldId, 
            'projectid' => $projectId,
            'bcourseid' =>$bcourseOldId,
        ];
        PdUtils::SaveMongoData($m_data, 'log-info');
        
        return $this->render('index',['tcourseId'=>$tcourseId,'error'=>$count==0?0:$error,'yida'=>$count==0?0:$yida,'count'=>$count,'userId'=>$userId]);
    }
   
    
    public function actionPaperQuestionListNew(){
        $type = isset($_REQUEST['type'])?$_REQUEST['type']:'';
        $tcourseId = $_REQUEST['tcourseId'];
        $userId = Yii::$app->user->identity->id;
        $session = Yii::$app->session;
        $joinCourseInfo=$session->get('joinCourseInfo');
        $projectId = empty($joinCourseInfo[$tcourseId]['project_id'])?PdUtils::getTcourseProjectId($tcourseId):$joinCourseInfo[$tcourseId]['project_id'];
        $tcourseOldId = empty($joinCourseInfo[$tcourseId]['t_old_id'])?PdUtils::getOldId('t_course_info',$tcourseId):$joinCourseInfo[$tcourseId]['t_old_id'];
        $bcourseOldId=empty($joinCourseInfo[$tcourseId]['b_old_id'])?PdUtils::getOldIdByTid($tcourseId):$joinCourseInfo[$tcourseId]['b_old_id'];
        $bcourseId = \app\models\TCourseInfo::findOne($tcourseId)['b_course_info_id'];
        
        if($type=='error'){//错题本
            $ques_sql="select q.* from t_quiz_student_ques_exercise e 
            left join t_quiz_question q on q.id = e.ques_id  
            where e.t_course_id='".$tcourseId."' and e.create_by='".$userId."' and e.is_correct='yesOrNo.no' and q.status='questionStatus.approved' and q.del_flag=0 and e.del_flag=0 group by q.id order by q.create_time asc";
        }else{
            $ques_sql="select q.* from t_quiz_course_ques_relation course_q 
            left join t_quiz_question q on q.id = course_q.question_id 
            where course_q.course_id='".$bcourseId."' and q.status='questionStatus.approved' and q.del_flag=0 and course_q.del_flag=0 group by q.id order by q.create_time asc";
        }
        
        $questionList = Yii::$app->db->createCommand($ques_sql)->queryAll();
        //已答题数
        $sql="select ques_id,answer,id exerciseId from t_quiz_student_ques_exercise where t_course_id=:t_course_id and create_by=:userId and del_flag=0";
        $answers = Yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userId,':t_course_id'=>$tcourseId])->queryAll();
        $answer = \yii\helpers\ArrayHelper::map($answers, 'ques_id', 'answer');
        $answerExercise = \yii\helpers\ArrayHelper::map($answers, 'ques_id', 'exerciseId');
        foreach($questionList as $k=>$q){
            //答案及解析
            $sql="select answ_code,answ_content,is_right from t_quiz_question_answer where del_flag = 0 and ques_id='".$q['id']."' order by answ_code asc";
            $answers = Yii::$app->db->createCommand($sql)->queryAll();
            $questionList[$k]['is_answer'] =  empty($answer)?'no':(empty($answer[$q['id']])?'no':'yes');
            $questionList[$k]['exerciseId'] =  empty($answerExercise)?'':(empty($answerExercise[$q['id']])?'':$answerExercise[$q['id']]);
            $questionList[$k]['answers'] =  $answers;
        }

        //查询是否是本人的试卷
        //防止学生之间互相复制链接答题
//        $url = Url::toRoute(['home/permission-denied']);//定义一个无权限页面
//        $resultInfo = TQuizResult::findOne($result);
//        if($resultInfo->create_by != $userId){
//            Yii::$app->getResponse()->redirect(Url::to($url));
//            Yii::$app->end();
//        }
        
        //用行为日志：打开学生考试测验页面
        $m_data=[
            'userid'=> \Yii::$app->user->identity->old_id,
            'time'=> date('Y-m-d H:i:s'),
            'ip'=> \Yii::$app->request->userIP,
            'equipment'=> PdUtils::EQUIPMENT_PC,
            'operation_code'=>'15010098',
            'operation_name'=>'试题练习学生考试测验之答卷页面',
            'courseid'=>$tcourseOldId,
            'objectid'=>$tcourseId, 
            'projectid' => $projectId,
            'bcourseid' =>$bcourseOldId,
        ];
        PdUtils::SaveMongoData($m_data, 'log-info');

        return $this->render('student_ques_exercise_list',array('tcourseId'=>$tcourseId,'questionList'=>$questionList,'answer'=>$answer));
    }

    /**
     * 删除附件
     */
    public function actionDeleteTestFile()
    {
        $fid = $_POST['fid'];
        $course_id = $_POST['course_id'];
        $uid = Yii::$app->user->identity->id;

        $sql = "update t_quiz_student_ques_exercise_file set del_flag=1,update_time=:update_time,update_by=:uid where id='" . $fid . "'";
        $res = Yii::$app->db->createCommand($sql)->bindValues([':uid'=>$uid,':update_time'=>date('Y-m-d H:i:s',time())])->execute();
        if ($res) {
            $session = Yii::$app->session;
            $joinCourseInfo=$session->get('joinCourseInfo');
            $projectId = empty($joinCourseInfo[$course_id]['project_id'])?PdUtils::getTcourseProjectId($course_id):$joinCourseInfo[$course_id]['project_id'];
            $t_old_id = empty($joinCourseInfo[$course_id]['t_old_id'])?PdUtils::getOldId('t_course_info',$course_id):$joinCourseInfo[$course_id]['t_old_id'];
            $b_old_id = empty($joinCourseInfo[$course_id]['b_old_id'])?PdUtils::getOldIdByTid($course_id):$joinCourseInfo[$course_id]['b_old_id'];
            $bcourseId=$joinCourseInfo[$course_id]['bCourseId'];
            //行为日志
            $m_data=[
                'userid' => Yii::$app->user->identity->old_id,
                'time' => date('Y-m-d H:i:s'),
                'ip' => \Yii::$app->request->userIP,
                'equipment' => PdUtils::EQUIPMENT_PC,
                'operation_code' => '19030017',
                'operation_name' => '删除考试测验附件',
                'courseid' => $t_old_id,
                'objectid' => $fid,
                'bcourseid' => $b_old_id,
                'projectid' => $projectId,
            ];
            PdUtils::SaveMongoData($m_data, 'log-info');
            return json_encode(array('status'=>true));
        } else {
            return json_encode(array('status'=>false));
        }

    }
    //选项题保存
    public function actionQuizResultAnswer(){
        $error=[];
        $tcourseId = isset($_REQUEST['tcourseId'])&&!empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error[]='开课ID不能为空';
        $answerId = isset($_REQUEST['answer_id'])&&!empty($_REQUEST['answer_id']) ? $_REQUEST['answer_id'] : $error[]='学生答案ID不能为空';
        $userId = isset($_REQUEST['userId'])&&!empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[]='学生ID不能为空';
        $answerContent = isset($_REQUEST['answerContent'])&&!empty($_REQUEST['answerContent']) ? $_REQUEST['answerContent'] : '';
        if(!empty($error)){
            $result=[
                'msg'=>'缺少请求参数',
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $bcourseId = \app\models\TCourseInfo::findOne($tcourseId)['b_course_info_id'];
            $transaction = \Yii::$app->db->beginTransaction();
            try {
            //获取问题答案的信息
            $quizAnswer = TQuizQuestionAnswer::findOne($answerId);
            //获取问题类型
            $question = TQuizQuestion::findOne($quizAnswer->ques_id);
            //查询这个题目下的所有正确答案
            $yes_sql = "select answ_code from t_quiz_question_answer where ques_id='".$quizAnswer->ques_id."' and is_right='yesOrNo.yes' and del_flag=0";
            $questionAnswerYes = \Yii::$app->db->createCommand($yes_sql)->queryColumn();

            //查询答题卡里面是否存储这条答案
            $resultAnswer = TQuizStudentQuesExercise::find()->where(':t_course_id=:t_course_id and del_flag=:d and ques_id=:ques_id and create_by=:userId',[':t_course_id'=>$tcourseId,':d'=>0,':ques_id'=>$quizAnswer->ques_id,':userId'=>$userId])->one();

            if(empty($resultAnswer)){
                $resultAnswer = new TQuizStudentQuesExercise();
                $resultAnswer->id = Uuid::uuid();
                $resultAnswer->b_course_id = $bcourseId;
                $resultAnswer->t_course_id = $tcourseId;
                $resultAnswer->ques_id = $quizAnswer->ques_id; 
                if($question->type=='questionType.singleChoice'  || $question->type=='questionType.yesOrNo'){
                    $resultAnswer->answer = $quizAnswer->answ_code;
                    $resultAnswer->is_correct = $quizAnswer->is_right;
                    if($resultAnswer->is_correct=='yesOrNo.yes'){//答案错误的不填写分数，新增加学生填写答案里的正确答案
                        $resultAnswer->points_awarded = 1;
                        $resultAnswer->answer_right = $quizAnswer->answ_code;
                    }else{
                        $resultAnswer->points_awarded = '';
                    }
                }elseif($question->type=='questionType.moreChoice'){
                    $resultAnswer->answer = $quizAnswer->answ_code;

                    if(in_array($resultAnswer->answer, $questionAnswerYes)){
                        $resultAnswer->is_correct = 'yesOrNo.yes';
                        $resultAnswer->answer_right = $quizAnswer->answ_code;
                    }else{
                        $resultAnswer->is_correct = 'yesOrNo.no';
                    }
                    $resultAnswerAll = array( $resultAnswer->answer_right);

                    $resultAnswerYes = array_intersect($questionAnswerYes, $resultAnswerAll);//查询两个数组相同的值，如果两个数组的相同值的个数和题目答案以及答题答案的个数相一致则证明学生选择的该题的全部答案为正确答案
                    if(count($resultAnswerYes)===count($questionAnswerYes) && count($resultAnswerYes)===count($resultAnswerAll)){
                        $resultAnswer->points_awarded = 1;
                    }else{
                        $resultAnswer->points_awarded = '';
                    } 
                }elseif($question->type=='questionType.fillIn'){
    //                    $resultAnswer->answer = $quizAnswer->answ_code."=".$quizAnswer->answ_content;
                    $resultAnswer->answer = $quizAnswer->answ_code."=".$answerContent;
                    $resultAnswer->is_correct = 'yesOrNo.yes';

                    if(trim($answerContent,'')==trim($quizAnswer->answ_content,' ')){
                        if(empty($resultAnswer->answer_right)){
                            $resultAnswer->answer_right = $quizAnswer->answ_code."=".$answerContent;
                        }else{
                            $resultAnswer->answer_right = $resultAnswer->answer_right ."&&". $quizAnswer->answ_code."=".$answerContent;
                        }
                        $resultAnswer->points_awarded = '';
                    }
                }else{
                    $resultAnswer->points_awarded = '';
                    $resultAnswer->answer = $answerContent;
                    $resultAnswer->is_correct = 'yesOrNo.yes';
                    if(trim($answerContent,'')==trim($quizAnswer->answ_content)){
                        $resultAnswer->answer_right = $answerContent;
                    }
    //                    $resultAnswer->answer_right = $resultAnswer->answer;
                }
                $resultAnswer->answer_time = date('Y-m-d H:i:s');
                $resultAnswer->create_by = $userId;
                $resultAnswer->create_time = date('Y-m-d H:i:s');
                $resultAnswer->del_flag = 0;      
                $resultAnswerRes = $resultAnswer->save();
                if($resultAnswerRes != false){
                    $resultAnswerFlag = TRUE;

                }else{
                    $resultAnswerFlag = false;
                }
                }else{
                    if($question->type =='questionType.moreChoice'){
                        $sAnswer = explode(',', $resultAnswer->answer);
                        if(!in_array($quizAnswer->answ_code, $sAnswer)){//判断这个答案和数据库存的是否一致
                            $resultAnswer->answer =$resultAnswer->answer.",". $quizAnswer->answ_code;
                        }
                        if(in_array($quizAnswer->answ_code,$questionAnswerYes)){
                            if(empty($resultAnswer->answer_right)){
                                $resultAnswer->answer_right = $quizAnswer->answ_code;
                            }else{
                                $resultAnswerRightAll = explode(',', $resultAnswer->answer_right.",".$quizAnswer->answ_code);
                                asort($resultAnswerRightAll);
        //                            $resultAnswer->answer_right = $resultAnswer->answer_right.",".$quizAnswer->answ_code;
                                $resultAnswer->answer_right = implode(',', $resultAnswerRightAll);
                            }
                        }
                        $resultAnswerAll = explode(',', $resultAnswer->answer);
                        asort($resultAnswerAll);
                        $resultAnswerAll = array_filter($resultAnswerAll);
                        $resultAnswerYes = array_intersect($questionAnswerYes, $resultAnswerAll);//查询两个数组相同的值，如果两个数组的相同值的个数和题目答案以及答题答案的个数相一致则证明学生选择的该题的全部答案为正确答案
                        if(count($resultAnswerYes)===count($questionAnswerYes) && count($resultAnswerYes)===count($resultAnswerAll)){
                            $resultAnswer->is_correct = 'yesOrNo.yes';
                        }else{
                            $resultAnswer->is_correct = 'yesOrNo.no';
                        }    
        //                    $resultAnswer->is_correct = $quizAnswer->is_right;
                        if($resultAnswer->is_correct=='yesOrNo.yes'){//答案错误的不填写分数
                            $resultAnswer->points_awarded = 1;
                        }else{
                            $resultAnswer->points_awarded = '';
                        }
                    }elseif($question->type =='questionType.fillIn'){
                        if(empty($resultAnswer->answer)){
                            $sAnswers = array();
                        }else{
                            $sAnswers = explode('&&', $resultAnswer->answer);
                        }
                        $sAnswer = array();
                        $sAnswerCode = array();
                        foreach($sAnswers as $k=>$v){
                            $a = explode('=', $v);
                            $sAnswer = array_merge($sAnswer,array($a[0]=>$a[1]));
                            $sAnswerCode = array_merge($sAnswerCode,array($a[0]));
                        }
                        //如果a=1，然后直接更改为a=2
                        if(!in_array($quizAnswer->answ_code, $sAnswerCode)){
                            if(empty($resultAnswer->answer)){
                                $resultAnswer->answer = $quizAnswer->answ_code."=".$answerContent;
                            }else{
                                $resultAnswer->answer = $resultAnswer->answer ."&&". $quizAnswer->answ_code."=".$answerContent;
                            }

                            $resultAnswer->is_correct = 'yesOrNo.yes';

                            if(trim($answerContent,' ')==trim($quizAnswer->answ_content,' ')){
                                if(empty($resultAnswer->answer_right)){
                                    $resultAnswer->answer_right = $quizAnswer->answ_code."=".$answerContent;
                                }else{
                                    $resultAnswer->answer_right = $resultAnswer->answer_right ."&&". $quizAnswer->answ_code."=".$answerContent;
                                }
                                $resultAnswer->points_awarded = '';
                            }

                        }else{
                            foreach($sAnswers as $v){
                                $a = explode('=', $v);
                                if($a[0]==$quizAnswer->answ_code){
                                    $str = array($quizAnswer->answ_code=>$answerContent);
                                    $sAnswer = array_merge($sAnswer,array($a[0]=>$answerContent));
                                }
                            }
                            foreach($sAnswer as $k=>$n){
                                $sAnswerNew[] = $k.'='.$n;
                            }
                            $resultAnswer->answer = implode('&&', $sAnswerNew);
                            $resultAnswer->is_correct = 'yesOrNo.yes';

                            if(trim($answerContent,' ')==trim($quizAnswer->answ_content,' ')){
                                if(empty($resultAnswer->answer_right)){
                                    $resultAnswer->answer_right = $quizAnswer->answ_code."=".$answerContent;
                                }else{
                                    $resultAnswer->answer_right = $resultAnswer->answer_right ."&&". $quizAnswer->answ_code."=".$answerContent;
                                }
                                $resultAnswer->points_awarded = '';
                            }
                        }
                    }elseif($question->type=='questionType.singleChoice' || $question->type=='questionType.yesOrNo'){
                        $resultAnswer->answer = $quizAnswer->answ_code;
                        $resultAnswer->is_correct = $quizAnswer->is_right;
                        if($resultAnswer->is_correct=='yesOrNo.yes'){//答案错误的不填写分数
                            $resultAnswer->points_awarded = 1;
                            $resultAnswer->answer_right =$resultAnswer->answer;
                        }else{
                            $resultAnswer->points_awarded = '';
                            $resultAnswer->answer_right ='';
                        }
                    }else{
                        $resultAnswer->points_awarded = '';
                        $resultAnswer->answer = $answerContent;
                        $resultAnswer->is_correct = 'yesOrNo.yes';

        //                    $resultAnswer->answer = $answerContent;
                        if(trim($answerContent,'')==trim($quizAnswer->answ_content)){
                            $resultAnswer->answer_right = $answerContent;
                        }
                    }
                    $resultAnswer->update_by = $userId;
                    $resultAnswer->update_time = date('Y-m-d H:i:s');
                    $resultAnswerRes = $resultAnswer->save();
                    if($resultAnswerRes != false){
                        $resultAnswerFlag = TRUE;
                    }else{
                        $resultAnswerFlag = false;
                    }
                }

                if($resultAnswerFlag){
                    $transaction->commit();
                    $sql="select count(*) from t_quiz_student_ques_exercise where t_course_id=:t_course_id and is_correct is not null and create_by=:userId and del_flag=0";
                    $resultAnswers = Yii::$app->db->createCommand($sql)->bindValues([':t_course_id'=>$tcourseId,':userId'=>$userId])->queryScalar();

                    $result = [
                        'msg' => '保存成功',
                        'ver' => '1.5.0',
                        'data' => ['num'=>$resultAnswers],
                        'success' => true,
                        'code' => '200'
                    ];
                }else{
                    $transaction->rollBack();
                    $result = [
                        'msg' => '保存失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '400'
                    ];
                }

            } catch (Exception $e) {
                $transaction->rollBack();
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
             Yii::$app->end(json_encode($result));
        }

    }
    //选项题删除
    public function actionQuizResultAnswerDelete(){
        $answerId = $_REQUEST['answer_id'];
        $tcourseId = $_REQUEST['tcourseId'];
        $userId = \Yii::$app->user->identity->id;
        $session = Yii::$app->session;
        $joinCourseInfo=$session->get('joinCourseInfo');
        $projectId = empty($joinCourseInfo[$tcourseId]['project_id'])?PdUtils::getTcourseProjectId($tcourseId):$joinCourseInfo[$tcourseId]['project_id'];
        $bcourseId = $session->get('joinCourseInfo')[$tcourseId]['bCourseId'];
        $tcourseOldId = empty($joinCourseInfo[$tcourseId]['t_old_id'])?PdUtils::getOldId('t_course_info',$tcourseId):$joinCourseInfo[$tcourseId]['t_old_id'];
        $bcourseOldId=empty($joinCourseInfo[$tcourseId]['b_old_id'])?PdUtils::getOldIdByTid($tcourseId):$joinCourseInfo[$tcourseId]['b_old_id'];

        $transaction = \Yii::$app->db->beginTransaction();
        try {
        //查询要删除的答案的answer_code 或者 answer_content
        $answer = TQuizQuestionAnswer::findOne($answerId);
        //查询本题的详细信息
        $qustionInfo = TQuizQuestion::findOne($answer->ques_id);
        //查询学生答题卡答案
        $model = TQuizStudentQuesExercise::find()->where(['t_course_id'=>$tcourseId,'ques_id'=>$answer->ques_id,'del_flag'=>0,'create_by'=>$userId])->one();

        //查询这个题目下的所有正确答案
        $yes_sql = "select answ_code from t_quiz_question_answer where ques_id='".$answer->ques_id."' and is_right='yesOrNo.yes' and del_flag=0";
        $questionAnswerYes = \Yii::$app->db->createCommand($yes_sql)->queryColumn();


        //查看此问题的题目类型
        $question = TQuizQuestion::findOne($model->ques_id);
        if($question->type=='questionType.moreChoice'){
            $ans = array();
//                $ans = explode(',', $model->answer);
            $ansb = explode(',',$model->answer);
            foreach($ansb as $n){
                $ans  = array_merge($ans,array($n=>$n));
            }
        }elseif($question->type=='questionType.fillIn'){
            $ans = array();
//                $ans = explode('&&',$model->answer);
            $ansb = explode('&&',$model->answer);
            foreach($ansb as $n){
                $exn = explode('=',$n);
                $ans  = array_merge($ans,array($exn[0]=>$exn[1]));
            }
        }else{
            $ans = "";
            $ans = $model->answer;
        }

        if(is_array($ans) && array_key_exists($answer->answ_code, $ans)){
            unset($ans[$answer->answ_code]);
            if($question->type=='questionType.moreChoice'){
                $resultAnswer = implode(',', $ans);
            }elseif($question->type=='questionType.fillIn'){
                if(!empty($ans)){
                foreach($ans as $k=>$v){
                    $resultAnswer[] = $k."=".$v;
                }
                $resultAnswer = implode('&&', $resultAnswer);
                }else{
                    $resultAnswer = '';
                }
            }
            //删除多选或者填空题最后的一个选项
            if(!empty($resultAnswer)){
                $model->answer = $resultAnswer;
            }else{
                $model->answer = null;
            }

        }else{
            if($question->type=='questionType.fillIn'){
//                    if(empty($model->answer))
//                    $model->del_flag = 1;
            }else{
                $model->answer = null;
            }
        }
        if(!empty($model->answer_right)){
            if($question->type=='questionType.moreChoice'){
                $ansRight = array();
//                $ans = explode(',', $model->answer);
                $ansbRight = explode(',',$model->answer_right);
                foreach($ansbRight as $nright){
                    $ansRight  = array_merge($ansRight,array($nright=>$nright));
                }
//                    $model->points_awarded = 0;

                $resultAnswerYes = array_diff($ansRight, $questionAnswerYes);
                if(empty($resultAnswerYes)){
                    $model->is_correct = 'yesOrNo.yes';
                }else{
                    $model->is_correct = 'yesOrNo.no';
                }
//                    $resultAnswer->is_correct = $quizAnswer->is_right;
                if($model->is_correct=='yesOrNo.yes'){//答案错误的不填写分数
                    $model->points_awarded = 1;
                }else{
                    $model->points_awarded = 0;
                }

            }elseif($question->type=='questionType.fillIn'){
                $ansRight = array();
//                $ans = explode('&&',$model->answer);
                $ansbRight = explode('&&',$model->answer_right);
                foreach($ansbRight as $nright){
                    $exnright = explode('=',$nright);
                    $ansRight  = array_merge($ansRight,array($exnright[0]=>$exnright[1]));
                }

            }else{
                $ansRight = "";
                $ansRight = $model->answer_right;
            }
            if(is_array($ansRight) && array_key_exists($answer->answ_code, $ansRight)){
                unset($ansRight[$answer->answ_code]);
                if($question->type=='questionType.moreChoice'){
                    $resultAnswerRight = implode(',', $ansRight);
//                        $resultAnswerYes = array_diff($ansRight, $questionAnswerYes);
                    $resultAnswerYes = array_diff($questionAnswerYes, $ansRight);
                    if(empty($resultAnswerYes)){
                        $model->is_correct = 'yesOrNo.yes';
                    }else{
                        $model->is_correct = 'yesOrNo.no';
                        $model->points_awarded = '';
                    }
                }elseif($question->type=='questionType.fillIn'){
                    if(!empty($ansRight)){
                    foreach($ansRight as $k=>$v){
                        $resultAnswerRight[] = $k."=".$v;
                    }
                    $resultAnswerRight = implode('&&', $resultAnswerRight);
                    }else{
                        $resultAnswerRight = '';
                    }
                }
                //删除多选或者填空题最后的一个选项
                if(!empty($resultAnswerRight)){
                    $model->answer_right = $resultAnswerRight;
                }else{
                    $model->answer_right = null;
                    $model->is_correct = 'yesOrNo.no';
//                        $model->del_flag = 1;
                }
            }
        }else{
            $model->is_correct = 'yesOrNo.no';
        }

        $model->update_by = $userId;
        $model->update_time = date('Y-m-d H:i:s');
        $res = $model->save();
        if($res !=false){
            $flag = 1;
        }else{
            $flag = 0;
        }
        $resultsql = 'select answer from t_quiz_student_ques_exercise where ques_id=:ques_id and t_course_id=:t_course_id and create_by=:userId and del_flag=0';
        $resultQuesAnswer= Yii::$app->db->createCommand($resultsql)->bindValues([':ques_id'=>$answer->ques_id,':t_course_id'=>$tcourseId,':userId'=>$userId])->queryScalar();
        if($flag){
            $transaction->commit();
            $sql="select count(*) from t_quiz_student_ques_exercise where ques_id=:ques_id and t_course_id=:t_course_id and create_by=:userId and del_flag=0";
            $resultAnswers = Yii::$app->db->createCommand($sql)->bindValues([':ques_id'=>$answer->ques_id,':t_course_id'=>$tcourseId,':userId'=>$userId])->queryScalar();
            $m_data=[
                'userid'=> \Yii::$app->user->identity->old_id,
                'time'=> date('Y-m-d H:i:s'),
                'ip'=> \Yii::$app->request->userIP,
                'equipment'=> PdUtils::EQUIPMENT_PC,
                'operation_code'=>'15010091',
                'operation_name'=>'试题练习删除暂存题目的答案',
                'courseid'=>$tcourseOldId,
                'objectid'=>$qustionInfo->old_id, 
                'projectid' => $projectId,
                'bcourseid' =>$bcourseOldId,
            ];
            PdUtils::SaveMongoData($m_data, 'log-info');
             echo json_encode(array('status'=>true,'num'=>$resultAnswers,'resultQuesAnswer'=>$resultQuesAnswer));
        }else{
            $transaction->rollBack();
            echo json_encode(array('status'=>false));
        }

        } catch (Exception $e) {
            $transaction->rollBack();
            echo json_encode(array('status'=>false));
        }

    }

    
    //保存试卷
    public function actionQuizResultAnswerSubmit(){
        $fid = isset($_REQUEST['fid'])?$_REQUEST['fid']:'';
        $time = date('Y-m-d H:i:s',time());
        //将考试测验文件表学生图片更新
        if(!empty($fid)){
            $str=rtrim($fid,',');
            if(strlen($str)>36){
                $str = implode("','", explode(',', $str));
            }

            $sql="update t_quiz_student_ques_exercise_file set del_flag=0,update_by=:uid,update_time=:update_time where id in('".$str."')";
            $res=\yii::$app->db->createCommand($sql)->bindValues([':uid'=>\yii::$app->user->identity->id,':update_time'=>$time])->execute();
        }else{
            $res = true;
        }
        $answerNum = $_REQUEST['answer_ques_num'];
        $totalNum = $_REQUEST['total_ques_num'];
        $tcourseId = $_REQUEST['tcourseId'];
        $userId = \Yii::$app->user->identity->id;
        
        $session = Yii::$app->session;
        $joinCourseInfo=$session->get('joinCourseInfo');
        $projectId = empty($joinCourseInfo[$tcourseId]['project_id'])?PdUtils::getTcourseProjectId($tcourseId):$joinCourseInfo[$tcourseId]['project_id'];
        $bcourseId = $session->get('joinCourseInfo')[$tcourseId]['bCourseId'];
        $tcourseOldId = empty($joinCourseInfo[$tcourseId]['t_old_id'])?PdUtils::getOldId('t_course_info',$tcourseId):$joinCourseInfo[$tcourseId]['t_old_id'];
        $bcourseOldId=empty($joinCourseInfo[$tcourseId]['b_old_id'])?PdUtils::getOldIdByTid($tcourseId):$joinCourseInfo[$tcourseId]['b_old_id'];
//        $Api = new ApiOperator();
//        $ApiUrl = \Yii::$app->params['apiUrl'];
//        $data = array(
//            'userId' => $userId,
//            'resultId' => $resultId,
//            'answerNum' => $answerNum,
//            'totalNum' => $totalNum,
//        );
//        $res=$Api->post($ApiUrl.'?r=Student/test-content/quiz-result-answer-submit',$data);
//        $res_arr=JsonParser::objectToArray($res);
//        $time = date('Y-m-d H:i:s');
//        $quizResult = TQuizResult::findOne($resultId);
//        if(!empty($res_arr['code'])&&$res_arr['code']==200){
        if($res !=false){
                //编辑mongo
//                $studentSubmitMongo = [
//                    'tasksEvaluationid'=>$quizResult->old_id,
//                    'userid'=> \Yii::$app->user->identity->old_id,
//                    'status'=>'已提交',
//                    'learningTasksid'=> PdUtils::getOldId('t_quiz_info', $quizId),
//                    'grater'=> \Yii::$app->user->identity->old_id,
//                    'modifiedtime'=> $time,
//                    'projectid' => $projectId,
//                    'bcourseid' =>$bcourseOldId,
//                ];
//                PdUtils::SaveMongoData($studentSubmitMongo, 'correcting');
                //用户行为日志：编辑
                $m_data=[
                    'userid'=> \Yii::$app->user->identity->old_id,
                    'time'=> $time,
                    'ip'=> \Yii::$app->request->userIP,
                    'equipment'=> PdUtils::EQUIPMENT_PC,
//                    'operation_code'=>'15010092',
//                    'operation_name'=>'提交考试测验',
                    'operation_code'=>'15020010',
                    'operation_name'=>'试题练习提交作业',
                    'courseid'=>$tcourseOldId,
                    'objectid'=>'',
                    'projectid' => $projectId,
                    'bcourseid' =>$bcourseOldId,
                ];
                PdUtils::SaveMongoData($m_data, 'log-info');
             echo json_encode(array('status'=>true));
        } else{
            echo json_encode(array('status'=>false));
        }
    }
    
    //错题列表
    public function actionErrorQuesList(){
        $userId = Yii::$app->user->identity->id;
        $tcourseId = $_REQUEST['tcourseId'];
        $bcourseId = \app\models\TCourseInfo::findOne($tcourseId)['b_course_info_id'];
        
//        $sql = "select e.* from t_quiz_student_ques_exercise e "
//                . "left join t_quiz_question q on q.id=e.ques_id "
//                . " where e.create_by=:userId and e.t_course_id=:tcourseId and b_course_id=:bcourseId and e.del_flag=0 and is_correct='yesOrNo.no' order by q.create_time asc";
        $sql = "select e.* from t_quiz_student_ques_exercise e "
                . "left join t_quiz_question q on q.id=e.ques_id "
                . " where e.create_by=:userId and e.t_course_id=:tcourseId and b_course_id=:bcourseId and e.del_flag=0 and (e.is_correct='yesOrNo.no' or q.type in('questionType.fillIn','questionType.shortAnswer','questionType.discuss','questionType.calculation')) order by q.create_time asc";
        $info = Yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userId,':tcourseId'=>$tcourseId,':bcourseId'=>$bcourseId])->queryAll();
        
        return $this->render('error_ques_list',['tcourseId' => $tcourseId,'quesList'=>$info,'total_num'=>count($info),'userId'=>$userId]);
    }
    
    public function actionErrorQuesListAjax() {
        $where = '';
        $session = \Yii::$app->session;

        //获取Datatables发送的参数 必要
        $draw = $_POST['draw'];
        //排序
        $order_column = $_POST['order']['0']['column'];//那一列排序，从0开始
        $order_dir = $_POST['order']['0']['dir'];//ase desc 升序或者降序
        //拼接排序sql
        $orderSql = "";
        if(isset($order_column)){
            $i = intval($order_column);
            switch($i){
                case 3;$orderSql = " order by q.quiz_type ".$order_dir;break;
                case 5;$orderSql = " order by q.quiz_status ".$order_dir;break;
                case 7;$orderSql = " order by q.create_time ".$order_dir;break;
                default;$orderSql = ' order by q.create_time desc';break;
            }
        }
        //搜索
        $search = str_replace(array(' ',"'"), '', $_POST['search']['value']);//获取前台传过来的过滤条件
        
        $tcourseId = Yii::$app->request->post('tcourseId','');
        $userId = Yii::$app->request->post('userId','');
        $total_num = Yii::$app->request->post('total_num','');
        
        //分页
        $start = $total_num>$_POST['length']?$_POST['start']:0;//从多少开始
        $length = $_POST['length'];//数据长度
        $limitSql = '';
        $limitFlag = isset($_POST['start']) && $length != -1 ;
        if ($limitFlag ) {
            $limitSql = " LIMIT ".intval($start).", ".intval($length);
        }
        if(!empty($quiz_type)){
            $where .= " and q.quiz_type='".$quiz_type."'";
        }
        if(strlen($search)>0){
            $where .= " and concat_ws('_',q.content) LIKE '%".$search."%'";
        }

        $sql = "select q.* from t_quiz_student_ques_exercise e "
                . "left join t_quiz_question q on q.id=e.ques_id "
                . "where e.t_course_id=:tcourseId and e.create_by=:create_by and (e.is_correct='yesOrNo.no' or q.type in('questionType.fillIn','questionType.shortAnswer','questionType.discuss','questionType.calculation')) and e.del_flag=0 ".$where." order by q.create_time asc";
        $count = Yii::$app->db->createCommand($sql)->bindValues([':tcourseId'=>$tcourseId,':create_by'=>$userId])->queryAll();
        $sql .= $limitSql;
        $quesList = Yii::$app->db->createCommand($sql)->bindValues([':tcourseId'=>$tcourseId,':create_by'=>$userId])->queryAll();

        if(!empty($quesList)){
            foreach($quesList as $key=>$val){
                //答案
                $sql="select answ_code,answ_content,is_right from t_quiz_question_answer where del_flag = 0 and ques_id='".$val['id']."' order by answ_code asc";
                $answers = Yii::$app->db->createCommand($sql)->queryAll();
                //知识点
                $sql="select p.name from t_quiz_question_knowledge_point ref left join b_course_knowledge_point p on p.id=ref.point_id "
                . "where ref.ques_id='".$val['id']."' and ref.del_flag=0 and p.del_flag=0 group by p.id";
                $knowledge = Yii::$app->db->createCommand($sql)->queryColumn();
                
                $quesList[$key]['answers'] = $answers;
                $quesList[$key]['knowledge'] = implode(',', $knowledge);

            }
        }
        //条件过滤后记录数 必要
        $recordsFiltered = 0;
        //表的总记录数 必要
        $recordsTotal = count($count);

        if(strlen($search)>0){
            $recordsFiltered = count($quesList);
        }else{
            $recordsFiltered = $recordsTotal;
        }
        
        $infoList=array();
        foreach($quesList as $key=>$val){
            $arr[0] = $key+1;
            $arr[1] = "<span title='".$val['content']."'>".$val['content']."<span>";
            $str = "<div style='overflow: hidden;text-overflow:ellipsis;white-space: nowrap;'><a class='answ_note' id='".$val['id']."' style='color:#2998e2'>"
                    . "<stong>解析：</strong>".$val['answ_note']."<br />"
                    . "<strong>答案：</strong>";
            $content = '';
            if($val['type']=='questionType.fillIn'){
                foreach ($val['answers'] as $k=>$v) {
                    if($k<2){
                    $content .= "[空".($k+1)."]：".$v['answ_content'];
                    }
                }
            }elseif($val['type']=='questionType.shortAnswer' || $val['type']=='questionType.discuss' || $val['type']=='questionType.calculation' ){
                foreach ($val['answers'] as $v) {
                        $content .= $v['answ_content'];
                }
            }else{
                foreach ($val['answers'] as $v) {
                    if ($v['is_right'] == 'yesOrNo.yes') {
                        $content .= $v['answ_code'];
                    }
                }
            }

            $arr[2] = $str .$content. "</a></div>";
            $arr[3]= \yii\helpers\Html::encode($val['knowledge']);
            $arr[4]= '<a title="重新答题" class="repeat_ques" id="'.$val['id'].'" ><button class="btn btn-warning">重新答题</button></a>';
            
            $infoList[]=$arr;
        }
        
        echo json_encode(array(
            "draw" => intval($draw),
            "recordsTotal" => intval($recordsTotal),
            "recordsFiltered" => intval($recordsFiltered),
            "data" => $infoList,
        ),JSON_UNESCAPED_UNICODE);exit;
    }
    
    //某道题的详细信息并答题
    public function actionErrorQuesOne(){
        $quesId = $_REQUEST['ques_id'];
        $tcourseId = $_REQUEST['tcourseId'];
        $userId = Yii::$app->user->identity->id;
        $bcourseId = \app\models\TCourseInfo::findOne($tcourseId)['b_course_info_id'];
        
        $sql = "select * from t_quiz_question where id=:ques_id";
        $questionList = Yii::$app->db->createCommand($sql)->bindValue(':ques_id', $quesId)->queryAll();
        //已答题数
        $sql="select ques_id,answer,id exerciseId from t_quiz_student_ques_exercise where t_course_id=:t_course_id and create_by=:userId and del_flag=0";
        $answers = Yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userId,':t_course_id'=>$tcourseId])->queryAll();
        $answer = \yii\helpers\ArrayHelper::map($answers, 'ques_id', 'answer');
        $answerExercise = \yii\helpers\ArrayHelper::map($answers, 'ques_id', 'exerciseId');
        foreach($questionList as $k=>$q){
            //答案及解析
            $sql="select answ_code,answ_content,is_right from t_quiz_question_answer where del_flag = 0 and ques_id='".$quesId."' order by answ_code asc";
            $answers = Yii::$app->db->createCommand($sql)->queryAll();
            $questionList[$k]['is_answer'] =  empty($answer)?'no':(empty($answer[$q['id']])?'no':'yes');
            $questionList[$k]['exerciseId'] =  empty($answerExercise)?'':(empty($answerExercise[$q['id']])?'':$answerExercise[$q['id']]);
            $questionList[$k]['answers'] =  $answers;
        }
        return $this->renderAjax('error_ques_one',array('tcourseId'=>$tcourseId,'questionList'=>$questionList,'answer'=>$answer));
    }
    
    //某道题的详细信息
    public function actionErrorQuesOneInfo(){
        $tcourseId = $_REQUEST['tcourseId'];
        $questionid = $_REQUEST['ques_id'];
        $question_sql = "select * from t_quiz_question where id='".$questionid."' and del_flag=0";
        $question = \Yii::$app->db->createCommand($question_sql)->queryAll();
        foreach($question as $k=>$v){
            $sql="select answ_code,answ_content,is_right from t_quiz_question_answer where del_flag = 0 and ques_id='".$v['id']."' order by answ_code asc";
            $answers = Yii::$app->db->createCommand($sql)->queryAll();
            $knowledge_sql = "select k.name from t_quiz_question_knowledge_point kr left join b_course_knowledge_point k on k.id=kr.point_id where kr.ques_id='".$v['id']."' and kr.course_id='".$tcourseId."' and kr.del_flag=0 and k.del_flag=0";
            $knowledge = Yii::$app->db->createCommand($knowledge_sql)->queryColumn();
            $question[$k]['knowledge']=(empty($knowledge)?"":(implode(',', $knowledge)));
            $question[$k]['answers']=$answers;
        }
        return $this->renderAjax('ques_info', ['tcourseId' => $tcourseId,'questionInfo'=> $question]);
    }
    
    
   //学员试卷阅览
    public function actionPaperQuestionListView(){
        //课程id与平台id
//        $tcourse_id = empty($_REQUEST['tcourseId'])?1:$_REQUEST['tcourseId'];
        $tcourse_id = $_REQUEST['tcourseId'];
        $userId = \Yii::$app->user->identity->id;
//        BaseController::checkUserAccess($course_id);
    	//接口公用信息
    	$Api = new ApiOperator();
    	$ApiUrl = \Yii::$app->params['apiUrl'];
    	//获取习题类型信息
    	$data = array();
    	$data['type'] = "questionType";
    	$res = $Api->post($ApiUrl."?r=base/type-list",$data);
    	$res_arr = JsonParser::objectToArray($res);
    	$questionTypeInfo = $res_arr['data']['list'];
        //获取习题类型数组信息
        $data = array();
        $data['type' ]= "questionType";
        $res = $Api->post($ApiUrl."?r=base/get-dictionary-type-array",$data);
        $res_arr = JsonParser::objectToArray($res);
        $questionTypeArr = $res_arr['data'];
        //获取习题难度数组信息
        $dat = array();
        $data['type'] = "questionDifficulty";
        $res = $Api->post($ApiUrl."?r=base/get-dictionary-type-array",$data);
        $res_arr = JsonParser::objectToArray($res);
        $questionDifficultyArr = $res_arr['data'];
    	//习题列表
    	$page = isset($_GET['page'])?$_GET['page']:1;
    	$pageSize = isset($_GET['per-page'])?$_GET['per-page']:5;
    	$keywords = isset($_POST['keywords'])?$_POST['keywords']:'';
    	$type = isset($_GET['questionType'])?$_GET['questionType']:'';
        $orderBy = isset($_GET['orderBy'])?$_GET['orderBy']:'';
        $session = \Yii::$app->session;
        $joinCourseInfo=$session->get('joinCourseInfo');
        $projectId = empty($joinCourseInfo[$tcourse_id]['project_id'])?PdUtils::getTcourseProjectId($tcourse_id):$joinCourseInfo[$tcourse_id]['project_id'];
        $bcourseId = $session->get('joinCourseInfo')[$tcourse_id]['bCourseId'];
        $tcourseOldId = empty($joinCourseInfo[$tcourse_id]['t_old_id'])?PdUtils::getOldId('t_course_info',$tcourse_id):$joinCourseInfo[$tcourse_id]['t_old_id'];
        $bcourseOldId=empty($joinCourseInfo[$tcourse_id]['b_old_id'])?PdUtils::getOldIdByTid($tcourse_id):$joinCourseInfo[$tcourse_id]['b_old_id'];
    	$data=array();
    	$data['page'] = $page;
    	$data['pageSize'] = $pageSize;
    	$data['keywords'] = $keywords;
    	$data['type'] = $type;
    	$data['tcourseId' ]= $_GET['tcourseId'];
        $data['quiz_id'] = $_GET['quiz_id'];
        $data['orderBy'] = $orderBy;
    	$data['project_id'] = $projectId;//联盟id
        $data['userId'] = $userId;
        $data['resultId'] = $_GET['resultId'];
    	$res = $Api->post($ApiUrl."?r=Student/test-content/paper-ques-list",$data);
    	$res_arr = JsonParser::objectToArray($res);
    	$questionListInfo = $res_arr['data'];
        $type=isset($type)?$type:'';
        //查询试卷标题
//        $paper_res = $Api->post($ApiUrl."?r=Student/test-content/paper-title",$data);
//    	$paper_arr_res = JsonParser::objectToArray($paper_res);
//        $paper = $paper_arr_res['data'];
        
        $paperScore_res = $Api->post($ApiUrl."?r=Student/test-content/paper-view-score",$data);
    	$paperScore_arr = JsonParser::objectToArray($paperScore_res);
    	$paperScore = $paperScore_arr['data'];
        
        //查询试卷标题以及试卷总分
        $paper_id = TQuizPaperRelation::find()->where(['quiz_id'=>$data['quiz_id'],'del_flag'=>0])->one()->paper_id;
        $paperResult = \app\models\TQuizPaper::findOne($paper_id);
        $info['paper_name'] = $paperResult->title;     
        $info['paper_score'] = $paperResult->total_score;     
        $info['pass_line'] = $paperResult->pass_line;     
        //学生姓名
        $quizResult = TQuizResult::findOne($data['resultId']);
        $user = \app\models\TBaseUserProfile::find()->where(['user_id'=>$userId,'del_flag'=>0])->one();
        $info['pet_name'] = $user->pet_name;
        $info['begin_time'] = $quizResult->begin_time;
        $info['end_time'] = $quizResult->end_time;
        
        //查询测验名称
        $quiz = TQuizInfo::findOne($data['quiz_id']);
         
        //用户行为日志：打开开课考试测验页面
        $m_data=[
            'userid'=> \Yii::$app->user->identity->old_id,
            'time'=> date('Y-m-d H:i:s'),
            'ip'=> \Yii::$app->request->userIP,
            'equipment'=> PdUtils::EQUIPMENT_PC,
            'operation_code'=>'10060063',
            'operation_name'=>'预览学生个人试卷',
            'courseid'=>$tcourseOldId,
            'objectid'=> PdUtils::getOldId('t_quiz_result', $_GET['resultId']), 
            'projectid' => $projectId,
            'bcourseid' =>$bcourseOldId,
        ];
        PdUtils::SaveMongoData($m_data, 'log-info');
        
        return $this->render('paper_question_list_view',['questionTypeInfo'=>$questionTypeInfo,'questionListInfo'=>$questionListInfo,'type'=>$type,'course_id'=>$tcourse_id,'questionTypeArr'=>$questionTypeArr,'questionDifficultyArr'=>$questionDifficultyArr,'questionType'=>$type,'resultId'=>$_GET['resultId'],'paperInfo'=>$info,'paperScore'=>$paperScore,'quiz'=>$quiz]);
        
    }
    

    
}
